package com.imay.videorecord.view.player;

import android.content.Context;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;

import com.imay.videorecord.filter.base.gpuimage.GPUImageFilter;
import com.imay.videorecord.utils.ImayCons;
import com.imay.videorecord.utils.ImayParams;



/**
 * Created by ZhouZeChao on 2017/1/4.
 */
public class FilteredVideoView extends GLSurfaceView implements OnFrameAvailableCallBack{
    private Context mContext;
    private MediaPlayer mMediaPlayer = null;
    private long time = 0;
    private MyCustomRenderer renderer;
    private boolean mediaPlayerInitialized = false;
    private String videoPath;
    private int mPosition = 0;

    private  FilteredVideoCallBack back;

    public FilteredVideoView(Context context) {
        super(context);
        setWillNotDraw(false);
        init();
        mContext = context;
        //startFilterChangeThread();
    }

    public FilteredVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
        init();
        mContext = context;
    }

    public void setFilter(final GPUImageFilter filter) {
        queueEvent(new Runnable() {
            @Override
            public void run() {
                renderer.setFilter(filter);
            }
        });
        requestRender();
    }

    public void stopVideo() {
        mMediaPlayer.pause();
        mMediaPlayer.stop();
    }

    /**
     * 设置音量
     * @param leftVolume
     * @param rightVolume
     */
    public void setVolume(float leftVolume, float rightVolume){
        mMediaPlayer.setVolume(leftVolume,rightVolume);
    }

    public void prepareVideo() {
        try {
            mMediaPlayer.prepareAsync();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    //mMediaPlayer.seekTo(mPosition);
                    //首先取得video的宽和高
                    int imageWidth = mediaPlayer.getVideoWidth();
                    int imageHeight = mediaPlayer.getVideoHeight();

                    if(imageWidth > ImayCons.screenW || imageHeight > ImayCons.screenW){
                        //如果video的宽或者高超出了当前屏幕的大小，则要进行缩放
                        float wRatio = (float)imageWidth/(float)ImayCons.screenW;
                        float hRatio = (float)imageHeight/(float)ImayCons.screenW;

                        //选择大的一个进行缩放
                        float ratio = Math.min(wRatio, hRatio);

                        imageWidth = (int)Math.ceil((float)imageWidth/ratio);
                        imageHeight = (int)Math.ceil((float)imageHeight/ratio);

                        /**
                         * 重塑滤镜时候的surfaceView用
                         */
                        ImayParams.imageWidth = imageWidth;
                        ImayParams.imageHeight = imageHeight;

                        /**
                         * 预备返回
                         */
                        if(back != null){
                            back.preparePlay(imageWidth,imageHeight);
                        }

                    }

                    mMediaPlayer.start();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void playVideo() {
        if(mediaPlayerInitialized){
            prepareVideo();
        }else{
            initMediaPlayer();
        }

        //mMediaPlayer.seekTo(mMediaPlayer.getCurrentPosition());
        //mMediaPlayer.start();
    }

    private void init() {
        setEGLContextClientVersion(2);

        getHolder().setFormat(PixelFormat.TRANSLUCENT);
        setEGLConfigChooser(8, 8, 8, 8, 16, 0);

        mMediaPlayer = new MediaPlayer();

        //initMediaPlayer();

        renderer = new MyCustomRenderer(getContext(),mMediaPlayer);
        setRenderer(renderer);
        renderer.setFrameAvailableCallBack(this);
    }

    private void initMediaPlayer() {
        if (mediaPlayerInitialized) {
            return;
        }

        mediaPlayerInitialized = true;

        try {
            mMediaPlayer.setDataSource(mContext,Uri.parse(videoPath));
            mMediaPlayer.setLooping(false);
            prepareVideo();

            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    onVideoPlaybackFinished();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 播放完成后
     */
    void onVideoPlaybackFinished() {
        if(back != null){
            back.playbackFinish();
        }
    }

    /**
     * 释放资源数据
     */
    public void release(){
        if(renderer != null){
            renderer.release();
            renderer = null;
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();

        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
        }
    }

    public void setVideoPath(String videoPath) {
        this.videoPath = videoPath;
    }

    /**
     * 重塑滤镜的状态
     * @param isRecording
     */
    public void changeRecordingState(boolean isRecording) {
        renderer.changeRecordingState(isRecording);
    }

    /**
     * 设置回调
     * @param back
     */
    public void setBack(FilteredVideoCallBack back) {
        this.back = back;
    }

    @Override
    public void callBack() {
        requestRender();
    }
}